/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Appearance,
  DeviceEventEmitter,
  ColorSchemeName,
} from 'react-native';
import type {ReactNode} from 'react';
import type {NativeStackNavigationProp} from '@react-navigation/native-stack';
import {FaceDetectionModule} from 'react-native-face-detection';

interface FaceDetectionResult {
  success: boolean;
  message?: string;
  faceCount?: number;
  timestamp?: number;
}

type RootStackParamList = {
  faceDetection: undefined;
  [key: string]: undefined;
};

interface FaceDetectionPageProps {
  navigation: NativeStackNavigationProp<RootStackParamList, 'faceDetection'>;
}

const FaceDetectionPage = ({navigation}: FaceDetectionPageProps): ReactNode => {
  const [colorScheme, setColorScheme] = useState<ColorSchemeName>(Appearance.getColorScheme());
  const [isDetecting, setIsDetecting] = useState<boolean>(false);
  const [detectionStatus, setDetectionStatus] = useState<string>('未扫描到人脸');
  const [faceDetected, setFaceDetected] = useState<boolean>(false);

  useEffect((): (() => void) => {
    console.log('[FaceDetectionPage] Module check:', !!FaceDetectionModule);

    const subscription = Appearance.addChangeListener(({colorScheme: newColorScheme}): void => {
      setColorScheme(newColorScheme);
    });

    // 使用 DeviceEventEmitter 监听事件 (RNOH TurboModule 使用 emitDeviceEvent)
    const eventListener = DeviceEventEmitter.addListener(
      'onFaceDetected',
      (result: FaceDetectionResult): void => {
        console.log('[FaceDetectionPage] Face detected event:', result);
        if (result.success && result.faceCount && result.faceCount > 0) {
          setFaceDetected(true);
          setDetectionStatus(`检测到 ${result.faceCount} 张人脸`);
        } else {
          setFaceDetected(false);
          setDetectionStatus('未扫描到人脸');
        }
      }
    );

    return (): void => {
      subscription.remove();
      eventListener.remove();
    };
  }, []);

  const startDetection = async (): Promise<void> => {
    if (!FaceDetectionModule) {
      console.error('[FaceDetectionPage] Module not found');
      setDetectionStatus('人脸检测模块未加载');
      return;
    }

    try {
      console.log('[FaceDetectionPage] Starting detection');
      setIsDetecting(true);
      setDetectionStatus('正在启动人脸检测...');

      // 调用原生模块启动活体检测
      // interactiveLiveness 会自动打开检测界面
      const result: FaceDetectionResult = await FaceDetectionModule.startFaceDetection();
      console.log('[FaceDetectionPage] Detection result:', result);

      // 检测完成后更新状态
      setIsDetecting(false);
      if (result.success) {
        setFaceDetected(true);
        setDetectionStatus(result.message || '人脸检测成功');
      } else {
        setFaceDetected(false);
        setDetectionStatus(result.message || '检测失败');
      }
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      console.error('[FaceDetectionPage] Detection error:', error);
      setDetectionStatus('检测失败: ' + errorMessage);
      setIsDetecting(false);
      setFaceDetected(false);
    }
  };

  const stopDetection = async (): Promise<void> => {
    if (!FaceDetectionModule) {
      return;
    }

    try {
      console.log('[FaceDetectionPage] Stopping detection');
      await FaceDetectionModule.stopFaceDetection();
      setIsDetecting(false);
      setFaceDetected(false);
      setDetectionStatus('未扫描到人脸');
    } catch (error: unknown) {
      console.error('[FaceDetectionPage] Stop error:', error);
    }
  };

  const goBack = (): void => {
    if (isDetecting) {
      stopDetection();
    }
    navigation.goBack();
  };

  const isDark: boolean = colorScheme === 'dark';

  return (
    <View
      style={[
        styles.container,
        {backgroundColor: isDark ? '#000' : '#fff'},
      ]}>
      {/* 返回按钮 */}
      <TouchableOpacity style={styles.backButton} onPress={goBack}>
        <Text style={styles.backButtonText}>← 返回</Text>
      </TouchableOpacity>

      {/* 标题 */}
      <Text style={[styles.title, {color: isDark ? '#fff' : '#000'}]}>
        人脸识别
      </Text>

      {/* 人脸识别圆形窗口 */}
      <View style={styles.detectionArea}>
        <View
          style={[
            styles.faceCircle,
            faceDetected ? styles.faceCircleActive : styles.faceCircleInactive,
          ]}>
          <View style={styles.faceOutline}>
            {/* 人形轮廓示意 */}
            <View style={styles.faceHead} />
            <View style={styles.faceBody} />
          </View>
        </View>
      </View>

      {/* 检测状态文字 */}
      <View style={styles.statusContainer}>
        <Text
          style={[
            styles.statusText,
            {
              color: faceDetected
                ? '#4CAF50'
                : isDark
                ? '#999'
                : '#666',
            },
          ]}>
          {detectionStatus}
        </Text>
      </View>

      {/* 控制按钮 */}
      <View style={styles.controlContainer}>
        {!isDetecting ? (
          <TouchableOpacity
            style={[styles.button, styles.startButton]}
            onPress={startDetection}>
            <Text style={styles.buttonText}>开始检测</Text>
          </TouchableOpacity>
        ) : (
          <TouchableOpacity
            style={[styles.button, styles.stopButton]}
            onPress={stopDetection}>
            <Text style={styles.buttonText}>停止检测</Text>
          </TouchableOpacity>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backButton: {
    position: 'absolute',
    top: 50,
    left: 20,
    zIndex: 10,
    padding: 10,
  },
  backButtonText: {
    fontSize: 18,
    color: '#007AFF',
    fontWeight: '600',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginTop: 56,
    marginBottom: 40,
  },
  detectionArea: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  faceCircle: {
    width: 280,
    height: 280,
    borderRadius: 140,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 4,
  },
  faceCircleInactive: {
    borderColor: '#ccc',
    backgroundColor: 'rgba(200, 200, 200, 0.1)',
  },
  faceCircleActive: {
    borderColor: '#4CAF50',
    backgroundColor: 'rgba(76, 175, 80, 0.1)',
  },
  faceOutline: {
    alignItems: 'center',
  },
  faceHead: {
    width: 80,
    height: 100,
    borderRadius: 40,
    borderWidth: 3,
    borderColor: '#666',
    marginBottom: 10,
  },
  faceBody: {
    width: 100,
    height: 60,
    borderTopLeftRadius: 50,
    borderTopRightRadius: 50,
    borderWidth: 3,
    borderColor: '#666',
    borderBottomWidth: 0,
  },
  statusContainer: {
    paddingVertical: 30,
    alignItems: 'center',
  },
  statusText: {
    fontSize: 18,
    fontWeight: '600',
  },
  controlContainer: {
    paddingHorizontal: 40,
    paddingBottom: 60,
  },
  button: {
    height: 50,
    borderRadius: 25,
    justifyContent: 'center',
    alignItems: 'center',
  },
  startButton: {
    backgroundColor: '#007AFF',
  },
  stopButton: {
    backgroundColor: '#FF3B30',
  },
  buttonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
});

export default FaceDetectionPage;
